package pl.register.android.activities.students.ui;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import pl.register.android.R;
import pl.register.android.student.Student;
import pl.register.android.util.StringUtils;
import pl.register.android.widget.listview.RefreshableAdapter;

import java.util.Collections;
import java.util.List;

/**
 * @author Mateusz Strzelecki
 * @since 2013-04-09
 */

public class StudentListAdapter extends RefreshableAdapter<Student> {

    public StudentListAdapter(Context context) {
        super(context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = inflater.inflate(R.layout.list_student_row, null);
            holder.tvOrdinalNumber = (TextView) convertView.findViewById(R.id.ordinal_number_text_view);
            holder.tvStudentName = (TextView) convertView.findViewById(R.id.student_name_text_view);
            holder.tvStudentPhoneNo = (TextView) convertView.findViewById(R.id.student_phone_number_text_view);
            holder.tvStudentCity = (TextView) convertView.findViewById(R.id.student_city_text_view);
            holder.tvClass = (TextView) convertView.findViewById(R.id.student_class_text_view);
            holder.tvStudentEmail = (TextView) convertView.findViewById(R.id.student_email_text_view);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        fillRow(holder, position);
        return convertView;
    }

    private void fillRow(ViewHolder holder, int position) {
        Student student = items.get(position);
        String oridnalNo = "" + (position + 1);
        holder.tvOrdinalNumber.setText(oridnalNo);
        holder.tvStudentName.setText(StringUtils.build(student.getFirstName(), " ", student.getLastName()));
        holder.tvStudentPhoneNo.setText(student.getPhoneNo());
        holder.tvStudentCity.setText(student.getCity());
        holder.tvClass.setText(student.getClassNo());
        holder.tvStudentEmail.setText(student.getEmailAddress());
    }

    @Override
    public void refreshItems(List<Student> newItems) {
        super.refreshItems(newItems);
        Collections.sort(items);
    }

    @Override
    public void refresh() {
        super.refresh();
        Collections.sort(items);
    }

    public static class ViewHolder {
        public TextView tvOrdinalNumber;
        public TextView tvStudentName;
        public TextView tvStudentPhoneNo;
        public TextView tvStudentCity;
        public TextView tvClass;
        public TextView tvStudentEmail;
    }
}